package no.knowit.eventorama.controller;

import java.util.List;
import java.util.logging.Logger;

import no.knowit.eventorama.dao.EventDAO;
import no.knowit.eventorama.dataobject.Event;
import no.knowit.eventorama.dataobject.Participant;
import no.knowit.eventorama.util.MailUtil;
import no.knowit.eventorama.util.XMPPUtil;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@Controller
public class EventoramaController {

	private static final Logger log = Logger
			.getLogger(EventoramaController.class.getName());

	@RequestMapping("/eventorama.do")
	public String hello(ModelMap model) {
		addDefaultAttributes(model);
		return "eventorama";
	}

	@RequestMapping(value = "/decline.do", method = RequestMethod.POST)
	public String decline(@RequestParam("eventId") String paramEventId,
			ModelMap model) {

		long eventId = Long.valueOf(paramEventId);
		User currentUser = getCurrentUser();

		log.info("decline: eventId=" + eventId + ", user="
				+ currentUser.getNickname());

		EventDAO eventDAO = new EventDAO();

		Event event = eventDAO.loadByKey(eventId);

		if (!event.userIsParticipant(currentUser)) {
			throw new IllegalStateException(
					"Cannot remove user from event. User "
							+ currentUser.getNickname()
							+ " is not participant.");

		}

		Participant participantToRemove = null;
		for (Participant participant : event.getParticipants()) {
			if (participant.getUser().equals(currentUser)) {
				participantToRemove = participant;
			}
		}

		event.getParticipants().remove(participantToRemove);

		eventDAO.save(event);

		addDefaultAttributes(model);
		return "redirect:/eventorama.do";
	}

	private void addDefaultAttributes(ModelMap model) {

		UserService userService = UserServiceFactory.getUserService();

		User currentUser = userService.getCurrentUser();
		model.addAttribute("currentUser", currentUser);

		model.addAttribute("loggedin", getCurrentUser() != null);
		model.addAttribute("logouturl", userService
				.createLogoutURL("/eventorama.do"));
		model.addAttribute("loginurl", userService
				.createLoginURL("/eventorama.do"));
		List<Event> allEvents = loadAllEvents();
		model.addAttribute("allEvents", allEvents);
		model.addAttribute("eventCount", allEvents.size());
	}

	@RequestMapping("/accept.do")
	public String accept(@RequestParam("eventId") String paramEventId,
			ModelMap model) {

		long eventId = Long.valueOf(paramEventId);
		User currentUser = getCurrentUser();
		EventDAO eventDAO = new EventDAO();

		Event event = eventDAO.loadByKey(eventId);

		if (event.userIsParticipant(currentUser)) {
			throw new IllegalStateException("Cannot add user to event. User "
					+ currentUser.getNickname() + " already participant.");
		}

		event.getParticipants().add(new Participant("", currentUser));

		eventDAO.save(event);

		JID jid = new JID(currentUser.getEmail());
		String chatMsg = "HELO!\nThe user " + currentUser.getNickname()
				+ " just accepted your event " + event.getTitle()
				+ ".\nHow nice!";
		
		if (!XMPPUtil.sendMessage(jid, chatMsg)) {
			MailUtil.sendMail("New participant for event " + event.getTitle(),
					chatMsg, event.getAuthor(), currentUser);
		}

		addDefaultAttributes(model);
		return "eventorama";

	}

	@RequestMapping(value = "/newevent.do", method = RequestMethod.POST)
	public String newEvent(@RequestParam("title") String title,
			@RequestParam("comment") String comment, ModelMap model) {

		System.out.println("newevent.do, title=" + title + ", comment="
				+ comment);

		User currentUser = getCurrentUser();

		EventDAO eventDAO = new EventDAO();

		Event event = new Event(title, comment, currentUser);

		event.getParticipants().add(new Participant("", currentUser));

		eventDAO.save(event);

		addDefaultAttributes(model);

		return "redirect:/eventorama.do";
	}

	private User getCurrentUser() {
		return UserServiceFactory.getUserService().getCurrentUser();
	}

	@RequestMapping("/deleteevent.do")
	public String deleteevent(@RequestParam("eventId") String paramEventId,
			ModelMap model) {

		System.out.println("deleteevent, eventID=" + paramEventId);
		User currentUser = getCurrentUser();

		Long eventId = Long.valueOf(paramEventId);

		EventDAO eventDAO = new EventDAO();

		Event event = eventDAO.loadByKey(eventId);
		if (!event.canBeDeletedByUser(currentUser)) {
			throw new SecurityException(
					"Event cannot be deleted. Event contains participants other than user and/ or has been created by another user");
		}

		eventDAO.removeById(eventId);

		addDefaultAttributes(model);
		return "eventorama";
	}

	private List<Event> loadAllEvents() {
		EventDAO eventDAO = new EventDAO();
		List<Event> allEvents = eventDAO.loadAll();
		return allEvents;
	}
}